package cn.edu.nju.software.action.book;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.ServletResponseAware;

import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings("serial")
public class UploadBookImageAction extends ActionSupport implements ServletResponseAware {
	
	private File picture;
	private String pictureContentType;
	private String pictureFileName;
	private String savePath;
	private HttpServletResponse response;
	
	public File getPicture() {
		return picture;
	}

	public void setPicture(File picture) {
		this.picture = picture;
	}

	public void setPictureContentType(String pictureContentType) {
		this.pictureContentType = pictureContentType;
	}

	public void setPictureFileName(String pictureFileName) {
		this.pictureFileName = pictureFileName;
	}

	public void setSavePath(String savePath) {
		this.savePath = savePath;
	}

	@Override
	public void setServletResponse(HttpServletResponse response) {
		this.response = response;
		response.setCharacterEncoding("UTF-8");
	}
	
	public void upload() throws Exception {
		String realPath = ServletActionContext.getServletContext().getRealPath("/");
		String picturePath = savePath + "\\" + System.currentTimeMillis() + pictureFileName;
		FileOutputStream fos = new FileOutputStream(realPath + picturePath);
		FileInputStream fis = new FileInputStream(picture);
		byte[] buffer = new byte[1024];
		int length = 0;
		while ((length=fis.read(buffer)) > 0) {
			fos.write(buffer, 0, length);
		}
		response.getWriter().write(picturePath.replace('\\', '/'));
	}

}
